package work.jame.blog.configuration.spring;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import work.jame.blog.configuration.filter.RequestLimitInterceptor;
import work.jame.blog.framework.limit.AbstractRequestLimitHandler;
import work.jame.blog.framework.limit.impl.BlackListRequestLimitHandler;
import work.jame.blog.framework.limit.impl.TooManyRequestLimitHandler;
import work.jame.blog.framework.limit.impl.WhiteListRequestLimitHandler;

import java.util.Objects;

/**
 * spring配置类
 *
 * @author Jame!
 * @date 2023/5/11 下午 10:49
 */
@Configuration
public class SpringConfig implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SpringConfig.applicationContext = applicationContext;
    }

    /**
     * 从spring容器中获取对象
     *
     * @param tClass 对象的Class类型
     * @param <T>    类泛型
     * @return 在spring容器中对象的实例
     */
    public static <T> T getBean(Class<T> tClass) {
        if (applicationContext == null) {
            throw new RuntimeException("applicationContext为null");
        }
        return applicationContext.getBean(tClass);
    }


    /**
     * spring 容器初始化完成回调
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
        if (Objects.isNull(event.getApplicationContext().getParent())) {
            //添加全局请求限流
            AbstractRequestLimitHandler handler1 = SpringConfig.getBean(TooManyRequestLimitHandler.class);
            AbstractRequestLimitHandler handler2 = SpringConfig.getBean(BlackListRequestLimitHandler.class);
            AbstractRequestLimitHandler handler3 = SpringConfig.getBean(WhiteListRequestLimitHandler.class);
            RequestLimitInterceptor.addGlobalRequestLimitHandler(handler1);
            RequestLimitInterceptor.addGlobalRequestLimitHandler(handler2);
            RequestLimitInterceptor.addGlobalRequestLimitHandler(handler3);

        }
    }


}
